<template>
  <div>
    <el-input disabled :value="$route.query.roleName"></el-input>
    <el-tree
      style="margin: 20px 0"
      ref="tree"
      :data="allPermissions"
      node-key="id"
      show-checkbox
      default-expand-all
      :props="{ children: 'children', label: 'name' }"
    />
    <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    <el-button @click="cancel">取消</el-button>
  </div>
</template>

<script>
export default {
  name: "roleAuth",
  data() {
    return {
      loading: false, //标识,防止重复提交
      allPermissions: []
    };
  },

  created() {
    this.init();
  },
  methods: {
    // 初始化
    init() {
      // 根据角色id获取
      const roleId = this.$route.params.id;
      this.getPermissions(roleId);
    },

    // 获取指定角色的权限列表
    getPermissions(roleId) {
      this.$API.permission.toAssign(roleId).then(result => {
        const allPermissions = result.data.children;
        this.allPermissions = allPermissions;
        const checkedIds = this.getCheckedIds(allPermissions);
        this.$refs.tree.setCheckedKeys(checkedIds);
      });
    },

    // 得到选中的id列表
    getCheckedIds(auths, initArr = []) {
      return auths.reduce((pre, item) => {
        if (item.select && item.level === 4) {
          pre.push(item.id);
        } else if (item.children) {
          this.getCheckedIds(item.children, initArr);
        }
        return pre;
      }, initArr);
    },

    // 保存权限列表
    save() {
      // 得到所有全选和半选的权限id的数组
      const checkedIds = this.$refs.tree.getCheckedKeys();
      const halfCheckedIds = this.$refs.tree.getHalfCheckedKeys();
      const ids = checkedIds.concat(halfCheckedIds).join(",");
      this.loading = true;
      // 请求给角色分配多个权限
      this.$API.permission.doAssign(this.$route.params.id, ids).then(result => {
        this.loading = false;
        this.$message.success("分配权限成功");
        // 必须在跳转前获取
        // 得到角色名称
        const roleName = this.$route.query.roleName;
        // 得到当前用户所属角色列表
        const roles = this.$store.getters.roles;
        // 跳转回角色列表路由
        this.$router.replace("/acl/role/list", () => {
          if (roles.includes(roleName)) {
            // window.location.reload()
          }
        });
      });
    },

      // 取消
    cancel() {
      this.$router.replace({ name: "Role" });
    }
  }
};
</script>

<style scoped></style>
